package com.joe.bibackend.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.joe.bibackend.bean.UserBean;
import com.joe.bibackend.bean.vo.UserRegisterVO;
import com.joe.bibackend.e.ResponseCode;
import com.joe.bibackend.response.NormalResponse;
import com.joe.bibackend.service.impl.UserBeanServiceImpl;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;


@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserBeanServiceImpl userBeanService;

    @PostMapping("/register")
    public NormalResponse<String> userRegister(@RequestBody UserRegisterVO userRegisterVO){
        if(null == userRegisterVO){
            return new NormalResponse<>(null,ResponseCode.FAILED_INFO);
        }

        QueryWrapper<UserBean> matchedUser = new QueryWrapper<>();
        matchedUser.eq("user_account",userRegisterVO.getUserAccount());
        UserBean selectUser = userBeanService.getOne(matchedUser);
        if(selectUser != null){
            return new NormalResponse<>(null,ResponseCode.REPEATED_REGISTER);
        }

        UserBean newUser = new UserBean();
        newUser.setUserAccount(userRegisterVO.getUserAccount());
        newUser.setUserRole(userRegisterVO.getUserRole());
        newUser.setUserPassword(userRegisterVO.getUserPassword());
        newUser.setUserScore(0);

        boolean save = userBeanService.save(newUser);
        if(save){
            return new NormalResponse<>(String.valueOf(newUser.getId()),ResponseCode.SUCCESS_REGISTER);
        }
        return new NormalResponse<>(null,ResponseCode.FAILED);

    }

    @PostMapping("/login")
    public NormalResponse<UserBean> userLogin(@RequestBody UserBean loginUser, HttpServletRequest request){

        if(null == loginUser){
            return new NormalResponse<>(null,ResponseCode.FAILED_INFO);
        }

        QueryWrapper<UserBean> matchedUser = new QueryWrapper<>();
        matchedUser.eq("user_account",loginUser.getUserAccount());
        matchedUser.eq("user_password",loginUser.getUserPassword());
        UserBean selectUser = userBeanService.getOne(matchedUser);
        if(selectUser == null){
            return new NormalResponse<>(null,ResponseCode.PASSWORD_NOT_MATCH);
        }

        selectUser.setUserPassword(null);
        request.getSession().setAttribute("userState",selectUser);
        return new NormalResponse<>(selectUser,ResponseCode.SUCCESS_LOGIN);
    }

    @GetMapping("/currentUser")
    public NormalResponse<UserBean> getCurrentUser(HttpServletRequest request){
        Object result = request.getSession().getAttribute("userState");
        if(result != null){
            return new NormalResponse<> ((UserBean) result,ResponseCode.SUCCESS_LOGIN);
        }
        return null;
    }

}
